<template>
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      :destroy-on-close="true"
      :width="!props.isReadonly ? '1100px' : '1100px'"
      :align-center="true"
      draggable
      style="min-width: 1100px"
      @close="closeDialog"
      class="maxhDialog"
    >
      <div v-loading="pageLoading" style="min-height: 400px">
        <div v-show="props.isReadonly || formData.repairStatus == 1">
          <el-tabs>
            <el-tab-pane label="基本信息"
              ><div>
                <!-- <h3
                  class="mb-[5px] mt-[-5px] c-[#333] text-[15px] font-600 lh-[28px]"
                >
                  设备信息
                </h3> -->
                <el-descriptions
                  title=""
                  :column="3"
                  size="default"
                  border
                  style="width: 99%; margin-bottom: 20px"
                >
                  <el-descriptions-item>
                    <template #label>
                      <div class="cell-item">设备名称</div>
                    </template>
                    <span
                      class="cursor-pointer decoration-underline"
                      @click="openDialogdetail({ id: formData.assetId })"
                      >{{ formData.assetName || "" }}</span
                    >
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template #label>
                      <div class="cell-item">设备编码</div>
                    </template>
                    {{ formData.assetCode || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item v-show="formData.assetTypeName">
                    <template #label>
                      <div class="cell-item">设备种类</div>
                    </template>
                    {{ formData.assetTypeName || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item v-if="formData.assetModelNo">
                    <template #label>
                      <div class="cell-item">品牌型号</div>
                    </template>
                    {{ formData.assetModelNo || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item v-if="formData.usingDepartmentName">
                    <template #label>
                      <div class="cell-item">使用部门</div>
                    </template>
                    {{ formData.usingDepartmentName || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item v-if="formData.usingPersonName">
                    <template #label>
                      <div class="cell-item">使用人</div>
                    </template>
                    {{ formData.usingPersonName || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item v-if="formData.locationName">
                    <template #label>
                      <div class="cell-item">设备位置</div>
                    </template>
                    {{ formData.locationName || "" }}
                  </el-descriptions-item>
                </el-descriptions>

                <h3
                  class="mb-[5px] mt-[-3px] c-[#333] text-[15px] font-600 lh-[28px]"
                >
                  故障信息
                </h3>
                <el-descriptions
                  title=""
                  :column="3"
                  size="default"
                  border
                  style="width: 99%; margin-bottom: 20px"
                >
                  <el-descriptions-item>
                    <template #label>
                      <div class="cell-item">报修时间</div>
                    </template>
                    {{ formData.repairTime || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template #label>
                      <div class="cell-item">故障时间</div>
                    </template>
                    {{ formData.timeOfFailure || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template #label>
                      <div class="cell-item">报修人</div>
                    </template>
                    {{ formData.repairUserName || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template #label>
                      <div class="cell-item">报修编号</div>
                    </template>
                    {{ formData.repairCode || "" }}
                    <el-tag
                      type="warning"
                      class="ml-[5px] mt-[-2px]"
                      v-if="formData.repairStatus == '0'"
                      >{{
                        dictionaryStore.filterDictName(
                          "EamRepairStatus",
                          formData.repairStatus
                        )
                      }}</el-tag
                    >
                    <el-tag
                      class="ml-[5px] mt-[-2px]"
                      v-if="
                        Number(formData.repairStatus) > 0 &&
                        Number(formData.repairStatus) < 4
                      "
                      >{{
                        dictionaryStore.filterDictName(
                          "EamRepairStatus",
                          formData.repairStatus
                        )
                      }}</el-tag
                    >
                    <el-tag
                      class="ml-[5px] mt-[-2px]"
                      type="info"
                      v-if="Number(formData.repairStatus) >= 4"
                      >{{
                        dictionaryStore.filterDictName(
                          "EamRepairStatus",
                          formData.repairStatus
                        )
                      }}</el-tag
                    >
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template #label>
                      <div class="cell-item">故障状态</div>
                    </template>
                    {{
                      dictionaryStore.filterDictName(
                        "EamFaultStatus",
                        formData.faultStatus
                      )
                    }}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template #label>
                      <div class="cell-item">故障等级</div>
                    </template>
                    <el-tag v-if="formData.repairLevel == '1'" type="danger">{{
                      dictionaryStore.filterDictName(
                        "EamFaultLevel",
                        formData.repairLevel
                      )
                    }}</el-tag>
                    <el-tag v-else>{{
                      dictionaryStore.filterDictName(
                        "EamFaultLevel",
                        formData.repairLevel
                      )
                    }}</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template #label>
                      <div class="cell-item">故障来源</div>
                    </template>
                    {{
                      dictionaryStore.filterDictName(
                        "EamFaultSource",
                        formData.repairSource
                      )
                    }}
                  </el-descriptions-item>
                  <el-descriptions-item :span="3">
                    <template #label>
                      <div class="cell-item">故障描述</div>
                    </template>
                    {{ formData.remarks || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item
                    v-if="formData.images && formData.images.length"
                    :span="3"
                  >
                    <template #label>
                      <div class="cell-item">故障图片</div>
                    </template>
                    <div style="margin-bottom: -10px">
                      <CommonUploadFile
                        :showText="false"
                        :isRead="true"
                        :files="formData.images"
                        :key="1"
                      />
                    </div>
                  </el-descriptions-item>
                </el-descriptions>
                <div>
                  <h3
                    class="mb-[5px] mt-[-3px] c-[#333] text-[15px] font-600 lh-[28px]"
                  >
                    维修信息
                  </h3>
                  <div
                    class="grey1-color flex justify-start"
                    style="margin-bottom: 12px; color: #c0c4cc"
                    v-if="
                      !formData.repairTeamName &&
                      !formData.repairTeamUserName &&
                      !formData?.answerTime &&
                      formData?.outSourcing != '1'
                    "
                  >
                    待维修人员响应，暂无信息
                  </div>
                  <el-descriptions
                    title=""
                    :column="3"
                    size="default"
                    border
                    v-else
                    style="width: 99%; margin-bottom: 20px"
                  >
                    <el-descriptions-item v-if="formData.answerTime">
                      <template #label>
                        <div class="cell-item">应答时间</div>
                      </template>
                      {{ formData.answerTime || "" }}
                    </el-descriptions-item>
                    <el-descriptions-item v-if="formData.repairStartTime">
                      <template #label>
                        <div class="cell-item">维修开始时间</div>
                      </template>
                      {{ formData.repairStartTime || "" }}
                    </el-descriptions-item>
                    <el-descriptions-item v-if="formData.repairEndTime">
                      <template #label>
                        <div class="cell-item">维修结束时间</div>
                      </template>
                      {{ formData.repairEndTime || "" }}
                    </el-descriptions-item>
                    <el-descriptions-item v-if="formData.faultMode">
                      <template #label>
                        <div class="cell-item">故障模式</div>
                      </template>
                      {{ formData.faultMode || "" }}
                    </el-descriptions-item>
                    <el-descriptions-item v-if="formData.faultPhenomenon">
                      <template #label>
                        <div class="cell-item">故障现象</div>
                      </template>
                      {{ formData.faultPhenomenon || "" }}
                    </el-descriptions-item>
                    <el-descriptions-item v-if="formData.faultReason">
                      <template #label>
                        <div class="cell-item">故障原因</div>
                      </template>
                      {{ formData.faultReason || "" }}
                    </el-descriptions-item>
                    <el-descriptions-item v-if="formData.faultPosition">
                      <template #label>
                        <div class="cell-item">故障部位</div>
                      </template>
                      {{ formData.faultPosition || "" }}
                    </el-descriptions-item>
                    <el-descriptions-item
                      :span="2"
                      v-if="formData.faultHandleMeasure"
                    >
                      <template #label>
                        <div class="cell-item">处理措施</div>
                      </template>
                      {{ formData.faultHandleMeasure || "" }}
                    </el-descriptions-item>
                    <el-descriptions-item v-if="formData.repairTeamName">
                      <template #label>
                        <div class="cell-item">维修班组</div>
                      </template>
                      <!-- {{ formData.repairTeamCode || "" }} - -->
                      {{ formData.repairTeamName || "" }}
                    </el-descriptions-item>
                    <el-descriptions-item
                      v-if="
                        formData.repairTeamUserName &&
                        (!formData?.repairOrderPersons ||
                          formData?.repairOrderPersons.length === 0)
                      "
                    >
                      <template #label>
                        <div class="cell-item">维修人员</div>
                      </template>
                      <span>
                        <!-- {{ formData.repairTeamUserEmpNo || "" }} - -->
                        {{ formData.repairTeamUserName || "" }}
                      </span>
                    </el-descriptions-item>
                    <el-descriptions-item
                      v-if="
                        formData?.repairOrderPersons &&
                        formData?.repairOrderPersons.length
                      "
                    >
                      <template #label>
                        <div class="cell-item">维修人员</div>
                      </template>
                      <span>
                        {{
                          getRepairOrderPersons(formData?.repairOrderPersons)
                        }}
                      </span>
                    </el-descriptions-item>
                    <el-descriptions-item v-if="formData.repairUseTime">
                      <template #label>
                        <div class="cell-item">维修用时</div>
                      </template>
                      {{ formData.repairUseTime || "" }}分钟
                    </el-descriptions-item>
                    <el-descriptions-item v-if="formData.outSourcing">
                      <template #label>
                        <div class="cell-item">是否委外</div>
                      </template>
                      <span v-show="formData?.outSourcing == '1'">是</span>
                      <span v-show="formData?.outSourcing != '1'">否</span>
                    </el-descriptions-item>
                    <el-descriptions-item
                      :span="3"
                      v-if="formData?.repairSituation"
                    >
                      <template #label>
                        <div class="cell-item">维修其他发现</div>
                      </template>
                      {{ formData.repairSituation || "" }}
                    </el-descriptions-item>
                    <el-descriptions-item
                      v-if="
                        formData.executeFiles && formData.executeFiles.length
                      "
                      :span="3"
                    >
                      <template #label>
                        <div class="cell-item">维修图片</div>
                      </template>
                      <div style="margin-bottom: -10px">
                        <CommonUploadFile
                          :showText="false"
                          :isRead="true"
                          :files="formData.executeFiles"
                          :key="3"
                        />
                      </div>
                    </el-descriptions-item>
                  </el-descriptions>
                </div>

                <!-- 模拟更换备件信息 -->
                <div v-if="formData.parts && formData.parts.length">
                  <h3
                    class="mb-[5px] mt-[-3px] c-[#333] text-[15px] font-600 lh-[28px]"
                  >
                    更换备件
                  </h3>

                  <el-table
                    :data="formData.parts"
                    highlight-current-row
                    border
                    :cell-style="{ 'text-align': 'center' }"
                  >
                    <el-table-column
                      label="备件编号"
                      prop="spareCode"
                      width="175"
                    />
                    <el-table-column label="备件名称" prop="spareName" />
                    <el-table-column
                      label="备件类型"
                      prop="spareType"
                      width="175"
                    >
                      <template #default="scope">
                        {{
                          dictionaryStore.filterDictName(
                            "SpareType",
                            scope.row.spareType
                          )
                        }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="使用数量"
                      prop="sparePartNumber"
                      width="175"
                    />
                    <el-table-column
                      label="数量单位"
                      prop="spareUnit"
                      width="175"
                    />
                  </el-table>
                </div></div
            ></el-tab-pane>
            <el-tab-pane label="操作历史">
              <div style="display: flex">
                <el-timeline
                  style="
                    max-height: 100%;
                    overflow: auto;
                    padding-left: 5px;
                    margin-top: 10px;
                    min-height: 400px;
                  "
                >
                  <el-timeline-item
                    v-for="self in operationRecordList"
                    :key="self.id"
                    :type="typeBack(self)"
                    size="large"
                    :timestamp="self.lastUpdateTime"
                  >
                    <div
                      style="
                        width: 100%;
                        word-break: break-all;
                        display: flex;
                        flex-direction: column;
                      "
                    >
                      <span style="font-weight: 400; font-size: 14px">
                        {{ self.lastUpdatedUserName }}
                        【{{ self.operateType }}】{{
                          self.operateType === "关闭" ||
                          self.operateType === "重新维修"
                            ? `&nbsp;&nbsp;原因：${self.operateResult}`
                            : ""
                        }}
                        {{
                          self.operateType === "转交" ||
                          self.operateType === "指派"
                            ? `&nbsp;&nbsp;${self.operateResult}`
                            : ""
                        }}</span
                      >
                    </div>
                  </el-timeline-item>
                </el-timeline>
                <div
                  style="
                    font-weight: 700;
                    font-size: 12px;
                    color: #a36c51;
                    position: absolute;
                    right: 15px;
                    top: 15px;
                    cursor: pointer;
                    height: 30px;
                    width: 50px;
                  "
                  @click="showOperationRecord"
                >
                  <i-ep-sort /> 排序
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <el-form
          v-show="!props.isReadonly && formData.repairStatus != 1"
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="120"
          style="width: 100%; margin-top: 10px"
        >
          <el-tabs v-model="activeTabsValue" type="border-card" class="eam_tabs"
            ><el-tab-pane label="设备/报修信息">
              <!-- <h3
              class="mb-[5px] mt-[-15px] c-[#333] text-[15px] font-600 lh-[28px]"
            >
              设备信息
            </h3> -->
              <el-descriptions
                title=""
                :column="3"
                size="default"
                border
                style="width: 100%; margin-bottom: 20px"
              >
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">设备名称</div>
                  </template>
                  <span
                    class="cursor-pointer decoration-underline"
                    @click="openDialogdetail({ id: formData.assetId })"
                    >{{ formData.assetName || "" }}</span
                  >
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">设备编码</div>
                  </template>
                  {{ formData.assetCode || "" }}
                </el-descriptions-item>
                <el-descriptions-item v-show="formData.assetTypeName">
                  <template #label>
                    <div class="cell-item">设备种类</div>
                  </template>
                  {{ formData.assetTypeName || "" }}
                </el-descriptions-item>
                <el-descriptions-item v-if="formData.assetModelNo">
                  <template #label>
                    <div class="cell-item">品牌型号</div>
                  </template>
                  {{ formData.assetModelNo || "" }}
                </el-descriptions-item>
                <el-descriptions-item v-if="formData.usingDepartmentName">
                  <template #label>
                    <div class="cell-item">使用部门</div>
                  </template>
                  {{ formData.usingDepartmentName || "" }}
                </el-descriptions-item>
                <el-descriptions-item v-if="formData.usingPersonName">
                  <template #label>
                    <div class="cell-item">使用人</div>
                  </template>
                  {{ formData.usingPersonName || "" }}
                </el-descriptions-item>
                <el-descriptions-item v-if="formData.locationName">
                  <template #label>
                    <div class="cell-item">设备位置</div>
                  </template>
                  {{ formData.locationName || "" }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">报修时间</div>
                  </template>
                  {{ formData.repairTime || "" }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">故障时间</div>
                  </template>
                  {{ formData.timeOfFailure || "" }}
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">报修人</div>
                  </template>
                  {{ formData.repairUserName || "" }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">报修编号</div>
                  </template>
                  {{ formData.repairCode || "" }}
                  <el-tag
                    type="warning"
                    class="ml-[5px] mt-[-2px]"
                    v-if="formData.repairStatus == '0'"
                    >{{
                      dictionaryStore.filterDictName(
                        "EamRepairStatus",
                        formData.repairStatus
                      )
                    }}</el-tag
                  >
                  <el-tag
                    class="ml-[5px] mt-[-2px]"
                    v-if="
                      Number(formData.repairStatus) > 0 &&
                      Number(formData.repairStatus) < 4
                    "
                    >{{
                      dictionaryStore.filterDictName(
                        "EamRepairStatus",
                        formData.repairStatus
                      )
                    }}</el-tag
                  >
                  <el-tag
                    class="ml-[5px] mt-[-2px]"
                    type="info"
                    v-if="Number(formData.repairStatus) >= 4"
                    >{{
                      dictionaryStore.filterDictName(
                        "EamRepairStatus",
                        formData.repairStatus
                      )
                    }}</el-tag
                  >
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">故障来源</div>
                  </template>
                  {{
                    dictionaryStore.filterDictName(
                      "EamFaultSource",
                      formData.repairSource
                    )
                  }}
                </el-descriptions-item>
                <el-descriptions-item :span="3">
                  <template #label>
                    <div class="cell-item">故障描述</div>
                  </template>
                  {{ formData.remarks || "" }}
                </el-descriptions-item>
                <el-descriptions-item
                  v-if="formData.images && formData.images.length"
                  :span="3"
                >
                  <template #label>
                    <div class="cell-item">故障图片</div>
                  </template>
                  <div style="margin-bottom: -10px">
                    <CommonUploadFile
                      :showText="false"
                      :isRead="true"
                      :files="formData.images"
                      :key="4"
                    />
                  </div>
                </el-descriptions-item>
              </el-descriptions>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="故障状态" prop="faultStatus">
                    <el-select
                      style="width: 100%"
                      v-if="!props.isReadonly"
                      v-model="formData.faultStatus"
                      placeholder="请选择故障状态"
                    >
                      <el-option
                        v-for="item in dictionaryStore.filterDictList(
                          'EamFaultStatus'
                        )"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>

                    <span v-else>{{
                      dictionaryStore.filterDictName(
                        "EamFaultStatus",
                        formData.faultStatus
                      )
                    }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="故障等级" prop="repairLevel">
                    <el-select
                      style="width: 100%"
                      v-if="!props.isReadonly"
                      v-model="formData.repairLevel"
                      placeholder="请选择故障等级"
                    >
                      <el-option
                        v-for="item in dictionaryStore.filterDictList(
                          'EamFaultLevel'
                        )"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>

                    <span v-else>{{
                      dictionaryStore.filterDictName(
                        "EamFaultLevel",
                        formData.repairLevel
                      )
                    }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="维修信息">
              <el-row>
                <el-col :span="8">
                  <el-form-item
                    label="应答时间"
                    prop="answerTime"
                    labelWidth="98px"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="formData.answerTime"
                      placeholder=""
                      disabled
                      clearable
                    />
                    <span v-else>{{ formData.answerTime }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="维修开始时间" prop="repairStartTime">
                    <el-date-picker
                      v-if="!props.isReadonly"
                      v-model="formData.repairStartTime"
                      value-format="YYYY-MM-DD HH:mm"
                      format="YYYY-MM-DD HH:mm"
                      time-format="HH:mm"
                      clearable
                      type="datetime"
                      placeholder="请选择维修开始时间"
                      @change="timeChange"
                    />
                    <span v-else>{{ formData.repairStartTime }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="维修结束时间" prop="repairEndTime">
                    <el-date-picker
                      v-if="!props.isReadonly"
                      v-model="formData.repairEndTime"
                      value-format="YYYY-MM-DD HH:mm"
                      format="YYYY-MM-DD HH:mm"
                      time-format="HH:mm"
                      clearable
                      type="datetime"
                      placeholder="请选择维修结束时间"
                      @change="timeChange"
                    />
                    <span v-else>{{ formData.repairEndTime }}</span>
                  </el-form-item>
                </el-col>

                <el-col :span="16">
                  <el-form-item
                    label="故障现象"
                    prop="faultPhenomenon"
                    labelWidth="98px"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="formData.faultPhenomenon"
                      placeholder="请输入故障现象"
                      clearable
                      ref="inputRefPhenomenon"
                      @focus="focusHandle(1)"
                      @clear="clearHandle(1)"
                    >
                      <template #append>
                        <el-button @click="openFaultDialog(1)">选择</el-button>
                      </template></el-input
                    >
                    <span v-else>{{ formData.faultPhenomenon }}</span>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="故障模式" prop="faultModeId">
                    <el-select
                      style="width: 100%"
                      v-if="!props.isReadonly"
                      v-model="formData.faultModeId"
                      placeholder="请选择故障模式"
                      clearable
                      @change="faultModeChange"
                    >
                      <el-option
                        v-for="item in faultModeList"
                        :key="item.id"
                        :label="item.faultMode"
                        :value="item.id"
                      />
                    </el-select>

                    <span v-else>{{
                      dictionaryStore.filterDictName(
                        "EamFaultStatus",
                        formData.faultModeId
                      )
                    }}</span>
                  </el-form-item>
                </el-col>

                <el-col :span="16">
                  <el-form-item
                    label="故障原因"
                    prop="faultReason"
                    labelWidth="98px"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="formData.faultReason"
                      placeholder="请输入故障原因"
                      clearable
                      ref="inputRefReason"
                      @focus="focusHandle(2)"
                      @clear="clearHandle(2)"
                    >
                      <template #append>
                        <el-button @click="openFaultDialog(2)">选择</el-button>
                      </template></el-input
                    >
                    <span v-else>{{ formData.faultReason }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="故障部位" prop="faultPosition">
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="formData.faultPosition"
                      placeholder="请输入故障部位"
                      clearable
                      ref="inputRefPosition"
                      @focus="focusHandle(4)"
                      @clear="clearHandle(4)"
                    >
                      <template #append>
                        <el-button @click="openFaultDialog(4)">选择</el-button>
                      </template></el-input
                    >
                    <span v-else>{{ formData.faultPosition }}</span>
                  </el-form-item>
                </el-col>

                <el-col :span="16">
                  <el-form-item
                    label="处理措施"
                    prop="faultHandleMeasure"
                    labelWidth="98px"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="formData.faultHandleMeasure"
                      placeholder="请输入故障处理措施"
                      clearable
                      ref="inputRefMeasure"
                      @focus="focusHandle(3)"
                      @clear="clearHandle(3)"
                    >
                      <template #append>
                        <el-button @click="openFaultDialog(3)">选择</el-button>
                      </template></el-input
                    >
                    <span v-else>{{ formData.faultHandleMeasure }}</span>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="维修班组" prop="repairTeamId">
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="formData.repairTeamName"
                      placeholder="请选择维修班组"
                      clearable
                      style="width: 100%"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item
                    label="维修其他发现"
                    prop="repairSituation"
                    labelWidth="98px"
                  >
                    <el-input
                      type="textarea"
                      v-if="!props.isReadonly"
                      v-model="formData.repairSituation"
                      placeholder="请输入维修其他发现"
                      show-word-limit
                      :maxlength="250"
                      :autosize="{ minRows: 2, maxRows: 3 }"
                      clearable
                    />
                    <span v-else>{{ formData.repairSituation }}</span>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                  <el-form-item label="维修人" prop="repairTeamUser">
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="formData.repairTeamUserName"
                      placeholder="请选择维修人"
                      clearable
                      style="width: 100%"
                      disabled
                    />
                  </el-form-item>
                </el-col> -->
                <el-col :span="8">
                  <el-form-item label="维修用时" prop="repairUseTime">
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="formData.repairUseTime"
                      placeholder="请选择维修开始/结束时间"
                    >
                      <template #append>
                        <el-button>分钟</el-button>
                      </template>
                    </el-input>
                    <span v-else>{{ formData.repairUseTime }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="维修人员" labelWidth="98px">
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="personId"
                      multiple
                      collapse-tags
                      collapse-tags-tooltip
                      placeholder="请选择维修人员"
                      style="width: 100%"
                      @change="orderPersonsChange"
                    >
                      <el-option
                        v-for="item in tMemberList"
                        :key="item.id"
                        :label="`${item.memberName}`"
                        :value="item.id"
                      />
                    </el-select>
                    <span v-else>{{
                      getRepairOrderPersons(formData?.repairOrderPersons)
                    }}</span>
                  </el-form-item>
                </el-col>

                <el-col :span="24">
                  <el-form-item
                    label="维修图片"
                    prop="executeFiles"
                    labelWidth="98px"
                  >
                    <CommonUploadFile
                      accept=".png,.jpeg,.jpg"
                      :isRead="props.isReadonly"
                      :files="formData.executeFiles"
                      @update-files="updateFormFiles"
                      :key="2"
                      folderName="eam/equ/eamRepairHandle"
                      v-if="formData.executeFiles.length"
                    />
                    <CommonUploadFile
                      v-else
                      accept=".png,.jpeg,.jpg"
                      :isRead="props.isReadonly"
                      :files="[]"
                      folderName="eam/equ/eamRepairHandle"
                      @update-files="updateFormFiles"
                    />
                  </el-form-item>
                </el-col>
                <!-- executeFiles -->
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="更换备件">
              <el-button
                type="primary"
                plain
                class="mb-3"
                @click="openSelectParts"
              >
                <i-ep-plus />
                新增</el-button
              >

              <el-table
                :data="formData.parts"
                highlight-current-row
                border
                :cell-style="{ 'text-align': 'center' }"
                class="parts_form_table"
                ref="dataTableRef"
                :height="`calc(70vh - 275px)`"
              >
                <el-table-column label="序号" type="index" width="60" />
                <el-table-column
                  label="备件编号"
                  prop="spareCode"
                  min-width="175"
                />
                <el-table-column
                  label="备件名称"
                  prop="spareName"
                  min-width="175"
                />
                <el-table-column
                  label="备件类型"
                  prop="spareType"
                  min-width="175"
                >
                  <template #default="scope">
                    {{
                      dictionaryStore.filterDictName(
                        "SpareType",
                        scope.row.spareType
                      )
                    }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="使用数量"
                  props="sparePartNumber"
                  min-width="150"
                  align="center"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'parts.' + $index + '.sparePartNumber'"
                      :rules="rules.sonsparePartNumber"
                      label-width="0"
                    >
                      <el-input
                        v-model="row.sparePartNumber"
                        placeholder="请输入使用数量"
                        clearable
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="数量单位"
                  prop="spareUnit"
                  min-width="120"
                />
                <el-table-column
                  fixed="right"
                  align="center"
                  label="操作"
                  width="120"
                >
                  <template #default="{ $index }">
                    <el-button
                      type="danger"
                      link
                      @click.stop="handleDelete($index)"
                    >
                      <i-ep-delete />
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            v-if="formData.repairStatus == '2' || formData.repairStatus == '1'"
            @click="openPrompt(8)"
            >转交</el-button
          >
          <el-button
            type="primary"
            v-if="
              props.userType == '1' &&
              (formData.repairStatus == '2' ||
                formData.repairStatus == '1' ||
                formData.repairStatus == '0')
            "
            @click="openPrompt(9)"
            >指派</el-button
          >
          <el-button
            v-if="
              formData.repairStatus == '2' ||
              formData.repairStatus == '1' ||
              formData.repairStatus == '0'
            "
            type="primary"
            @click="openPrompt(10)"
            >委外</el-button
          >
          <el-button
            v-if="
              props.isReadonly &&
              (formData.repairStatus == '1' || formData.repairStatus == '2')
            "
            type="primary"
            @click="openPrompt(6)"
            >故障关闭</el-button
          >
          <el-button
            type="primary"
            v-if="formData.repairStatus == '0'"
            @click="openPromptNew(1)"
            >应答</el-button
          >
          <el-button
            type="primary"
            v-if="!props.isReadonly && formData.repairStatus == '1'"
            @click="openPromptNew(2)"
            >开始维修</el-button
          >
          <el-button
            type="primary"
            v-if="!props.isReadonly && formData.repairStatus == '2'"
            @click="handleSubmit(2)"
            >维修完成</el-button
          >
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit(1)"
            >保 存</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      v-model="showImport"
      :title="
        promptStatus === 8
          ? `转交信息`
          : promptStatus === 9
          ? `指派信息`
          : '提示'
      "
      destroy-on-close
      :width="450"
      draggable
      align-center
      class="showImport"
    >
      <!-- 转交和指派form -->
      <el-form v-if="promptStatus === 8 || promptStatus === 9">
        <el-form-item label="维修班组" :label-width="80">
          <el-select
            v-model="transferInfo.repairTeamId"
            placeholder="请选择维修班组"
            clearable
            @change="(id:any) => changeCrew(id, 2)"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in crewList"
              :key="item.id"
              :label="`${item.teamName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维修人" :label-width="80">
          <el-select
            v-model="transferInfo.repairTeamUser"
            placeholder="请选择维修人"
            clearable
            :disabled="transferInfo.repairTeamId === ''"
            @change="(id:any) => changeMember(id, 2)"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in tMemberList"
              :key="item.id"
              :label="`${item.memberName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 委外form -->
      <el-form v-else-if="promptStatus === 10">
        <el-form-item label="委外商" :label-width="80">
          <el-select
            v-model="supplierInfo.supplierId"
            placeholder="请选择委外商"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in supplierList"
              :key="item.id"
              :label="item.partnerName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 故障关闭 -->
      <el-form v-else-if="promptStatus === 6">
        <el-form-item label="故障原因" :label-width="80">
          <el-input
            v-model="promptReason"
            :placeholder="promptText"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <div v-else>
        {{ promptText }}
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelImport">取消</el-button>
          <el-button type="primary" @click="confirmImport(promptStatus)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设备信息查看 -->
    <equdeviceinfo-edit
      :visible="deviceDialog.visible"
      :title="deviceDialog.title"
      :data="deviceDialog.data"
      :is-readonly="deviceDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 添加更换备件列表信息 -->
    <common-sparepart-new-select
      v-model:visible="partsSelect.visible"
      :data="partsSelect.data"
      :isMultiple="true"
      :assetKind="props.assetKind"
      :eldIds="partsSelect.eldIds"
      @echo-info="getPartsSelect"
    />

    <!-- 故障现象选择 -->
    <eam-fault-phenomeon-select
      :visible="phenomenonDialog.visible"
      :faultModeId="formData.faultModeId"
      :faultModeList="faultModeList"
      @change-visible="(val: boolean, data: any)=>applyChangeVisible(val, data, 1)"
    />

    <!-- 故障原因选择 -->
    <eam-fault-reason-select
      :visible="reasonDialog.visible"
      :faultPhenomenonId="formData.faultPhenomenonId"
      @change-visible="(val: boolean, data: any)=>applyChangeVisible(val, data, 2)"
    />

    <!-- 故障处理措施选择 -->
    <eam-fault-measure-select
      :visible="measureDialog.visible"
      :faultReasonId="formData.faultReasonId"
      @change-visible="(val: boolean, data: any)=>applyChangeVisible(val, data, 3)"
    />

    <!-- 故障部位选择 -->
    <eam-fault-position-select
      :visible="positionDialog.visible"
      :assetTypeId="formData.assetTypeId"
      :assetKind="formData.assetKind"
      @change-visible="(val: boolean, data: any)=>applyChangeVisible(val, data, 4)"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { getCrewMemberListApi, getCrewListApi } from "@/utils/commonData";
import { useUserStore } from "@/store/modules/user";
import { getSupplierList, getFaultModeListApi } from "@/utils/commonData";
import { validateNumber, validateNumberCanNull } from "@/utils/commonHooks";
import dayjs from "dayjs";

defineOptions({
  name: "EAMREPAIREHANDLEBYMEEDIT",
  inheritAttrs: false,
});

const userStore = useUserStore();
const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  assetKind: {
    type: Number,
    default: null,
  },
  // 报修来源 按照字典表来 EamFaultSource
  repairSource: {
    type: String,
    default: "1",
  },
  // 1 组长（看所有的）   2 普通员工（看自己的和未应答的）
  userType: {
    type: String,
    default: "",
  },
});

const activeTabsValue = ref("1");
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      if (formRef.value?.clearValidate) {
        formRef.value?.clearValidate();
      }
    }, 50);
  }
);

/** 打开备件选择器方法   start **/
const partsSelect = reactive<DialogOption>({
  visible: false,
  data: [],
  eldIds: [],
});
// 打开 备件选择器弹窗
function openSelectParts() {
  const ids: any = [];
  formData.parts?.map((e: any) => {
    ids.push(e.sparePartId);
  });
  partsSelect.eldIds = ids;
  partsSelect.data = [];
  partsSelect.visible = true;
}

const dataTableRef = ref();
// 接收 备件选择器回调参数
function getPartsSelect(options: any) {
  options.forEach((item: any) => {
    formData.parts.push({
      // id: item.id,
      spareType: item.spareType,
      spareCode: item.spareCode,
      spareName: item.spareNmae,
      spareUnit: item.spareUnit,
      sparePartNumber: "",
      sparePartId: item.id,
    });
  });

  setTimeout(() => {
    const tableBodyWrapperView = dataTableRef.value.$el.querySelector(
      ".el-scrollbar__view"
    );
    if (tableBodyWrapperView.offsetHeight) {
      dataTableRef.value.setScrollTop(tableBodyWrapperView.offsetHeight);
    }
  }, 500);
}

/** 删除行 */
const handleDelete = (index: any) => {
  formData.parts.splice(index, 1);
};

/** 打开备件选择器方法   end **/

// 领用弹窗显隐
const inputRefPhenomenon = ref();
const inputRefReason = ref();
const inputRefMeasure = ref();
const inputRefPosition = ref();
function focusHandle(type: number) {
  if (type === 1 && formData.faultPhenomenonId) {
    inputRefPhenomenon.value.blur();
  }
  if (type === 2 && formData.faultReasonId) {
    inputRefReason.value.blur();
  }
  if (type === 3 && formData.faultHandleMeasureId) {
    inputRefMeasure.value.blur();
  }
  if (type === 4 && formData.faultPositionId) {
    inputRefPosition.value.blur();
  }
}

function clearHandle(type: number) {
  if (type === 1) {
    formData.faultPhenomenonId = "";
    formData.faultPhenomenon = "";
  } else if (type === 2) {
    formData.faultReasonId = "";
    formData.faultReason = "";
  } else if (type === 3) {
    formData.faultHandleMeasureId = "";
    formData.faultHandleMeasure = "";
  } else if (type === 4) {
    formData.faultPositionId = "";
    formData.faultPosition = "";
  }
}

// 故障现象弹窗
const phenomenonDialog = ref({
  visible: false,
});

// 故障原因弹窗
const reasonDialog = ref({
  visible: false,
});

// 故障处理措施弹窗
const measureDialog = ref({
  visible: false,
});

// 故障部位弹窗
const positionDialog = ref({
  visible: false,
});

function openFaultDialog(type: number) {
  if (type === 1) {
    if (!formData.faultModeId) {
      ElMessage.error("请先选择故障模式");
    } else {
      phenomenonDialog.value.visible = true;
    }
  } else if (type === 2) {
    reasonDialog.value.visible = true;
  } else if (type === 3) {
    measureDialog.value.visible = true;
  } else if (type === 4) {
    positionDialog.value.visible = true;
  }
}

const applyChangeVisible = (val: boolean, data: any, type: number) => {
  if (data && type === 1) {
    formData.faultPhenomenonId = data.id || "";
    formData.faultPhenomenon = data.faultPhenomenon || "";
  }
  if (data && type === 2) {
    formData.faultReasonId = data.id || "";
    formData.faultReason = data.faultReason || "";
  }
  if (data && type === 3) {
    formData.faultHandleMeasureId = data.id || "";
    formData.faultHandleMeasure = data.faultHandleMeasure || "";
  }
  if (data && type === 4) {
    formData.faultPositionId = data.id || "";
    formData.faultPosition = data.positionName || "";
  }
  if (type === 1) phenomenonDialog.value.visible = val;
  if (type === 2) reasonDialog.value.visible = val;
  if (type === 3) measureDialog.value.visible = val;
  if (type === 4) positionDialog.value.visible = val;
};

const realRules = {
  faultModeId: [
    { required: true, message: "请选择故障模式", trigger: "change" },
  ],
  repairStartTime: [
    { required: true, message: "请选择维修开始时间", trigger: "blur" },
    { validator: validateStartTime, trigger: "change" },
  ],
  repairEndTime: [
    { required: true, message: "请选择维修结束时间", trigger: "blur" },
    { validator: validateEndTime, trigger: "change" },
  ],
  faultPhenomenon: [
    { required: true, message: "请输入故障现象", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],

  faultReason: [
    { required: true, message: "请输入故障原因", trigger: "blur" },
    { min: 1, max: 128, message: "长度在 1 到 128 个字符", trigger: "blur" },
  ],
  faultHandleMeasure: [
    { required: true, message: "请输入故障处理措施", trigger: "blur" },
    { min: 1, max: 128, message: "长度在 1 到 128 个字符", trigger: "blur" },
  ],
  repairUseTime: [
    {
      validator: validateNumberCanNull,
      trigger: "blur",
    },
  ],
  sonsparePartNumber: [
    {
      validator: validateNumberCanNull,
      trigger: "blur",
    },
  ],
};

const elderRules = {
  faultModeId: [],
  repairStartTime: [],
  repairEndTime: [],
  repairUseTime: [
    {
      validator: validateNumberCanNull,
      trigger: "blur",
    },
  ],
  faultPhenomenon: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  faultReason: [
    { min: 1, max: 128, message: "长度在 1 到 128 个字符", trigger: "blur" },
  ],
  faultHandleMeasure: [
    { min: 1, max: 128, message: "长度在 1 到 128 个字符", trigger: "blur" },
  ],
  repairTime: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonsparePartNumber: [
    {
      validator: validateNumberCanNull,
      trigger: "blur",
    },
  ],
};

let rules = reactive({
  assetName: [{ required: true, message: "请选择设备", trigger: "blur" }],
  faultStatus: [
    { required: true, message: "请选择故障状态", trigger: "change" },
  ],
  repairLevel: [
    { required: true, message: "请选择故障等级", trigger: "change" },
  ],
  faultModeId: [],
  repairStartTime: [],
  repairEndTime: [],
  faultPhenomenon: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  faultReason: [
    { min: 1, max: 128, message: "长度在 1 到 128 个字符", trigger: "blur" },
  ],
  faultHandleMeasure: [
    { min: 1, max: 128, message: "长度在 1 到 128 个字符", trigger: "blur" },
  ],
  repairTime: [],
  repairUseTime: [
    {
      validator: validateNumberCanNull,
      trigger: "blur",
    },
  ],
  repairSituation: [
    {
      min: 1,
      max: 255,
      message: "长度在 1 到 255 个字符",
      trigger: "blur",
    },
  ],
  repairUserName: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  repairTeamId: [{ message: "请选择维修班组", trigger: "change" }],
  repairTeamUser: [{ message: "请选择维修人", trigger: "change" }],
  sonsparePartNumber: [
    {
      validator: validateNumberCanNull,
      trigger: "blur",
    },
  ],
});

const formRef = ref(ElForm);

let formData: any = reactive({
  id: "",
  // 设备信息
  assetId: "",
  assetName: "",
  assetCode: "",
  assetTypeName: "",
  assetModelNo: "",
  assetBrandName: "",
  usingDepartmentName: "",
  usingPersonName: "",
  locationName: "",
  // 故障信息
  images: [],
  parts: [],
  executeFiles: [],
  repairOrderPersons: [],
  faultStatus: "",
  repairLevel: "",
  remarks: "",

  // 维修信息
  repairTeamId: "",
  repairTeamCode: "",
  repairTeamName: "",
  repairTeamUser: "",
  repairTeamUserName: "",
  repairTeamUserEmpNo: "",

  // 以下为原生数据
  version: "",
  // assetTypeId: "",
  repairTime: "",
  timeOfFailure: "",
  repairUser: userStore.user.userId,
  repairUserName: userStore.user.userName,
  repairCode: "",
  repairUseTime: "", // 最新维修耗时
  // faultStatus: "",
  // repairLevel: "",
  // repairTeamId: "",
  // repairTeamUser: "",
  answerTime: "",
  repairStartTime: "",
  repairEndTime: "",
  faultMode: "",
  faultModeId: "",
  faultPhenomenon: "",
  faultPhenomenonId: "",
  faultReason: "",
  faultReasonId: "",
  faultPosition: "",
  faultPositionId: "",
  faultHandleMeasure: "",
  faultHandleMeasureId: "",
  repairSituation: "",
  repairStatus: "",
  outSourcing: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  assetKind: props.assetKind,
  repairSource: props.repairSource,
});

watch(
  () => props.data,
  async (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      getRepairInfo(newVal?.id);
    } else {
      formData.assetModelNo = "";
      formData.images = [];
      formData.parts = [];
      formData.executeFiles = [];
      formData.repairOrderPersons = [];

      formData.assetKind = props.assetKind;
      formData.repairSource = props.repairSource;
      formData.repairUserName = userStore.user.userName;
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.repairTime = "";
  formData.timeOfFailure = "";
  formData.repairUser = userStore.user.userId;
  formData.repairUserName = userStore.user.userName;
  formData.repairCode = "";
  formData.answerTime = "";
  formData.repairStartTime = "";
  formData.repairEndTime = "";
  formData.faultMode = "";
  formData.faultModeId = "";
  formData.faultPhenomenon = "";
  formData.faultPhenomenonId = "";
  formData.faultReason = "";
  formData.faultReasonId = "";
  formData.faultPosition = "";
  formData.faultPositionId = "";
  formData.faultHandleMeasure = "";
  formData.faultHandleMeasureId = "";
  formData.repairSituation = "";
  formData.repairStatus = "";
  formData.outSourcing = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.assetKind = props.assetKind;

  formData.assetId = "";
  formData.assetName = "";
  formData.assetCode = "";
  formData.assetTypeName = "";
  formData.assetModelNo = "";
  formData.assetBrandName = "";
  formData.usingDepartmentName = "";
  formData.usingPersonName = "";
  formData.locationName = "";
  formData.images = [];
  formData.parts = [];
  formData.executeFiles = [];
  formData.repairOrderPersons = [];

  formData.faultStatus = "";
  formData.repairLevel = "";
  formData.remarks = "";
  formData.repairTeamId = "";
  formData.repairTeamCode = "";
  formData.repairTeamName = "";
  formData.repairTeamUser = "";
  formData.repairTeamUserName = "";
  formData.repairTeamUserEmpNo = "";
  formData.repairSource = props.repairSource;
}

const loading = ref(false);

/** 维修单保存提交 */
function handleSubmit(type: number) {
  formRef.value.clearValidate();
  // 确认提交时增加校验
  if (type === 2) {
    Object.assign(rules, { ...realRules });
  } else if (type === 1) {
    Object.assign(rules, { ...elderRules });
  }
  formRef.value
    .validate(async (valid: any) => {
      if (valid) {
        loading.value = true;
        const text = type == 1 ? "保存" : "维修";
        await request({
          url: "/eam/eamrepairorder/save",
          method: "post",
          data: formData,
        }).finally(() => {
          loading.value = false;
        });
        if (type === 2) {
          openPrompt(3);
        } else {
          ElMessage.success(text + `成功`);
          closeDialog();
          emit("reset-table", formData.id);
        }
        // 校验恢复
        Object.assign(rules, { ...elderRules });
      } else {
        ElMessage.error("请先完成基础信息");
        activeTabsValue.value = "1";
      }
    })
    .catch(() => {
      // ElMessage.error("请先完成校验");
    });
}

// 图片处理
function updateFormFiles(val: []) {
  formData.executeFiles = val;
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

//班组
const crewList = ref(<any>[]);
//人员
const memberList = ref(<any>[]);

// 转交人员
const tMemberList = ref(<any>[]);

const changeCrew = async (id: any, type: number) => {
  if (type === 1) {
    formData.repairTeamId = id;
    crewList.value.forEach((item: any) => {
      if (item.id === id) {
        formData.repairTeamCode = item.teamCode;
        formData.repairTeamName = item.teamName;
      }
    });
    formData.repairTeamUserName = "";
    formData.repairTeamUserEmpNo = "";
    formData.repairTeamUser = "";

    memberList.value =
      (await getCrewMemberListApi({ id: formData.repairTeamId })) || [];
  } else {
    transferInfo.repairTeamId = id;
    crewList.value.forEach((item: any) => {
      if (item.id === id) {
        transferInfo.repairTeamCode = item.teamCode;
        transferInfo.repairTeamName = item.teamName;
      }
    });
    transferInfo.repairTeamUserName = "";
    transferInfo.repairTeamUserEmpNo = "";
    transferInfo.repairTeamUser = "";

    tMemberList.value =
      (await getCrewMemberListApi({ id: transferInfo.repairTeamId })) || [];
  }
};
async function getCrews() {
  crewList.value = (await getCrewListApi({ teamType: "1" })) || [];
}
const changeMember = (id: any, type: number) => {
  if (type === 1) {
    formData.repairTeamUser = id;
    memberList.value.forEach((item: any) => {
      if (item.id === id) {
        formData.repairTeamUserEmpNo = item.memberEmpNo;
        formData.repairTeamUserName = item.memberName;
      }
    });
  } else {
    transferInfo.repairTeamUser = id;
    tMemberList.value.forEach((item: any) => {
      if (item.id === id) {
        transferInfo.repairTeamUserEmpNo = item.memberEmpNo;
        transferInfo.repairTeamUserName = item.memberName;
      }
    });
  }
};

// 转交/指派功能数据定义
const transferInfo = reactive({
  repairTeamId: "",
  repairTeamCode: "",
  repairTeamName: "",
  repairTeamUser: "",
  repairTeamUserEmpNo: "",
  repairTeamUserName: "",
});

// 委外供应商数据定义
const supplierInfo = reactive({
  supplierId: "",
  supplierName: "",
});

const promptText = ref("");
const promptReason = ref("");
const promptStatus: any = ref(null);
function getStatusText(status: number) {
  promptReason.value = "";
  if (status === 1) {
    promptText.value = `请确认，是否应答编号为${formData.repairCode}的报修单?`;
  } else if (status === 2) {
    promptText.value = `请确认，编号为${formData.repairCode}的报修单是否开始维修?`;
  } else if (status === 3) {
    promptText.value = `请确认，编号为${formData.repairCode}的报修单是否维修完成?`;
  } else if (status === 6) {
    promptText.value = `请填写故障关闭原因`;
  }
}
// 选择作业
const showImport = ref(false);
function openPrompt(status: number) {
  promptStatus.value = status;
  getStatusText(status);
  showImport.value = true;
}

function openPromptNew(status: number) {
  promptStatus.value = status;
  confirmImport(status);
}

// 取消选择
function cancelImport() {
  showImport.value = false;
  promptText.value = "";
  Object.assign(transferInfo, {
    repairTeamId: "",
    repairTeamCode: "",
    repairTeamName: "",
    repairTeamUser: "",
    repairTeamUserEmpNo: "",
    repairTeamUserName: "",
  });
  Object.assign(supplierInfo, {
    supplierId: "",
    supplierName: "",
  });
}

// 状态扭转
function changeStatus() {
  return new Promise(async (resolve, reject) => {
    const res = await request({
      method: "post",
      url: "/eam/eamrepairorder/updateStatus",
      data: {
        id: formData.id,
        repairStatus: promptStatus.value,
        memo: promptStatus.value === 6 ? promptReason.value : "",
      },
    }).catch((e) => {});
    resolve(res);
  });
}

// 转交
function transferHandle() {
  return new Promise(async (resolve, reject) => {
    const res = await request({
      method: "post",
      url: "/eam/eamrepairorder/transmit",
      data: {
        id: formData.id,
        ...toRaw(transferInfo),
      },
    }).catch((e) => {});
    resolve(res);
  });
}

// 指派
function transferAssign() {
  return new Promise(async (resolve, reject) => {
    const res = await request({
      method: "post",
      url: "/eam/eamrepairorder/assign",
      data: {
        id: formData.id,
        ...toRaw(transferInfo),
      },
    }).catch((e) => {});
    resolve(res);
  });
}

// 委外
function transferSupplier() {
  return new Promise(async (resolve, reject) => {
    const res = await request({
      method: "post",
      url: "/eam/eamrepairorder/start/outSourcing",
      data: {
        id: formData.id,
        ...toRaw(supplierInfo),
      },
    }).catch((e) => {});
    resolve(res);
  });
}

// 追加加工单
async function confirmImport(promptStatus: number) {
  if (promptStatus === 6 && !promptReason.value) {
    ElMessage.error("请填写故障关闭原因");
    return;
  }
  if (
    (promptStatus === 8 || promptStatus === 9) &&
    !transferInfo.repairTeamId
  ) {
    ElMessage.error("请选择维修班组");
    return;
  }

  if (
    (promptStatus === 8 || promptStatus === 9) &&
    !transferInfo.repairTeamUserEmpNo
  ) {
    ElMessage.error("请选择维修人");
    return;
  }

  if (promptStatus === 10 && !supplierInfo.supplierId) {
    ElMessage.error("请选择委外商");
    return;
  }
  let code = null;
  if (promptStatus === 8) {
    const codeObj: any = await transferHandle();
    code = codeObj.code;
  } else if (promptStatus === 9) {
    const codeObj: any = await transferAssign();
    code = codeObj.code;
  } else if (promptStatus === 10) {
    const codeObj: any = await transferSupplier();
    code = codeObj.code;
  } else {
    const codeObj: any = await changeStatus();
    code = codeObj.code;
  }
  if (code === 200) {
    cancelImport();
    ElMessage.success("操作成功");
    if (promptStatus === 2 || promptStatus === 1) {
      // 刷新当前页面
      emit("reset-isReadonly", false);
      getRepairInfo(formData.id);
    } else {
      closeDialog();
      emit("reset-table", formData.id);
    }
  } else {
    ElMessage.error("操作失败");
  }
}

onMounted(() => {
  getCrews();
  getPartnerList();
  getFaultModeList();
});

// 获取委外商列表
const supplierList = ref();
async function getPartnerList() {
  supplierList.value = (await getSupplierList("")) || [];
}

// 获取故障模式列表
const faultModeList = ref();
async function getFaultModeList() {
  faultModeList.value = (await getFaultModeListApi(null)) || [];
}
function faultModeChange(e: string) {
  if (e) {
    faultModeList.value?.forEach((item: any) => {
      if (item.id === e) {
        formData.faultMode = item.faultMode;
      }
    });
  } else {
    formData.faultModeId = "";
    formData.faultMode = "";
  }
}

const deviceDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getDeviceInfo(id: string) {
  request({
    url: `/eam/equAssetInfo/get/${id}`,
    method: "get",
  })
    .then((data) => {
      deviceDialog.data = data.data;
      deviceDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开资产台账表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  deviceDialog.title = "资产台账详情";
  getDeviceInfo(roleObj.id);
  deviceDialog.readvisible = true;
}

// 弹窗隐藏
function changeVisible(value: boolean) {
  deviceDialog.visible = value;
  if (!value) {
    deviceDialog.data = {};
  }
}

// 查询工单详情
const pageLoading = ref(false);
async function getRepairInfo(id: string) {
  pageLoading.value = true;
  request({
    url: `/eam/eamrepairorder/get/${id}`,
    method: "get",
    data: {
      assetKind: props.assetKind,
    },
  })
    .then(async (data) => {
      Object.assign(formData, data.data);
      // 数组判空处理
      if (!formData.images) formData.images = [];
      if (!formData.parts) formData.parts = [];
      if (!formData.executeFiles) formData.executeFiles = [];
      if (!formData.repairOrderPersons) formData.repairOrderPersons = [];

      // 品牌型号赋值
      const { assetModelNo, assetBrandName } = data.data;
      if (assetModelNo && assetBrandName) {
        formData.assetModelNo = `${assetModelNo}-${assetBrandName}`;
      } else if (assetModelNo && !assetBrandName) {
        formData.assetModelNo = `${assetModelNo}`;
      } else if (!assetModelNo && assetBrandName) {
        formData.assetModelNo = `${assetBrandName}`;
      }
      // 班组人员数据获取
      getCrews();
      memberList.value =
        (await getCrewMemberListApi({ id: formData.repairTeamId })) || [];

      // 维修人员员逻辑添加
      tMemberList.value =
        (await getCrewMemberListApi({ id: formData.repairTeamId })) || [];

      console.log("tMemberList", tMemberList.value);

      // 给维修人员默认值
      if (
        formData.repairTeamUserName &&
        (formData.repairOrderPersons.length === 0 ||
          !formData.repairOrderPersons)
      ) {
        formData.repairOrderPersons = [
          {
            personId: formData.repairTeamUser,
            personName: formData.repairTeamUserName,
            personEmpNo: formData.repairTeamUserEmpNo,
          },
        ];
      }

      let nameIds: any = [];
      if (formData.repairOrderPersons && formData.repairOrderPersons?.length) {
        formData.repairOrderPersons?.map((e) => {
          nameIds.push(e.personId);
        });
        personId.value = nameIds;
      } else {
        personId.value = [];
      }
      // 获取历史记录接口
      getHistoryList();
      pageLoading.value = false;
    })
    .catch((res) => {
      console.log(res);
      pageLoading.value = false;
    });
}

// 校验时间
function validateEndTime(rule: any, value: any, callback: any) {
  if (
    (formData.repairStartTime && value < formData.repairStartTime) ||
    value == formData.repairStartTime
  ) {
    callback(new Error("结束时间不能小于或等于开始时间"));
  } else {
    callback();
  }
}
// 校验
function validateStartTime(rule: any, value: any, callback: any) {
  if (
    (formData.repairEndTime && value > formData.repairEndTime) ||
    value == formData.repairEndTime
  ) {
    callback(new Error("开始时间不能大于或等于结束时间"));
  } else {
    callback();
  }
}

function timeChange() {
  formData.repairUseTime = "";
  if (formData.repairEndTime && formData.repairStartTime) {
    formRef.value.validateField("repairEndTime");
    formRef.value.validateField("repairStartTime");
    if (
      dayjs(formData.repairEndTime).valueOf() >
      dayjs(formData.repairStartTime).valueOf()
    ) {
      formData.repairUseTime = dayjs(formData.repairEndTime).diff(
        dayjs(formData.repairStartTime),
        "minute"
      );
    }
  }
}

function getRepairOrderPersons(arr: any) {
  let res: any = [];
  arr?.map((e: any) => {
    res.push(e?.personName);
  });
  return res.join("/");
}

// 选择其他班组成员
const personId = ref([]);

function orderPersonsChange(ids) {
  let resArr: any = [];
  ids?.map((self: string) => {
    const res = memberList.value.filter((e) => e.id === self) || [];
    res.length &&
      resArr.push({
        personId: res[0].id,
        personEmpNo: res[0].memberEmpNo,
        personName: res[0].memberName,
      });
  });
  formData.repairOrderPersons = resArr;
  console.log("resArr", resArr);
}

// 历史记录获取
const operationRecordList = ref<any>([]);
async function getHistoryList() {
  const res = await request({
    method: "get",
    url: `/eam/eamworkorderrecord/getByOrderId/${formData.id}`,
    data: {},
  }).catch((e) => {});
  operationRecordList.value = res?.data || [];
  console.log("getHistoryList", res);
}

// 排序
const showOperationRecord = () => {
  if (operationRecordList.value.length > 0) {
    operationRecordList.value.reverse();
  }
};

// 返回类型
const typeBack = (data: any) => {
  if (data.operateType == "关闭" || data.operateType == "重新维修") {
    return "danger";
  } else if (
    data.operateType == "转交" ||
    data.operateType == "指派" ||
    data.operateType == "委外开始"
  ) {
    return "warning";
  } else if (data.operateType == "完成确认") {
    return "success";
  } else {
    return "primary";
  }
};
</script>

<style scoped lang="scss">
:deep(.maxhDialog .el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
  padding: 10px 20px;
}
.el-form-item {
  margin-bottom: 15px;
  word-break: break-all;
  .el-input-group__append .el-button {
    padding: 0 10px;
  }
}
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 120px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
  word-break: break-all;
}
:deep(.el-upload--picture-card) {
  width: 130px;
  height: 130px;
}
:deep(.el-upload-list__item) {
  width: 130px;
  height: 130px;
}
:deep(.showImport .el-dialog__body) {
  padding: 20px;
}
:deep(.eam_tabs .el-tabs__content) {
  overflow-y: auto;
  height: 480px;
}

.parts_form_table {
  :deep(tbody .el-table__cell) {
    padding: 0 !important;
  }
  :deep(.el-form-item) {
    margin: 13px 0 14px 0 !important;
  }
}
</style>
